package com.blb.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/admin/*")
public class AdminFilter implements Filter {

    private String[] urls = {"/admin/view/login", "/admin/login"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //白名单放行
        String uri = req.getRequestURI();
        for (String url : urls) {
            if(uri.contains(url)){
                filterChain.doFilter(req, resp);
                return;
            }
        }

        //1.获取session对象
        HttpSession session = req.getSession();
        //2.从session中获取user标记
        Object admin = session.getAttribute("SessionAdmin");
        //4.为null则重定向登录页面，否则放行
        if(admin==null){
            resp.sendRedirect("/admin/view/login");
            return;
        }
        //放行请求
        filterChain.doFilter(req, resp);
    }

    @Override
    public void destroy() {

    }
}
